package com.scfire.message


import grails.transaction.Transactional

import java.util.HashMap;
import java.util.Set;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.cloopen.rest.sdk.CCPRestSDK.BodyType;
import com.scfire.baseInfo.Gson
import com.scfire.message.SmsVerification;


@Transactional
class CCPSMSService {

	CCPRestSDK restAPI
	
	def CCPSMSService(){
		restAPI = new CCPRestSDK();
		
		restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
		
		restAPI.setAccount("8a48b5514f1702fd014f2a5e5fd01abf", "1c9714e3a8794edf81a93601e51dbcd6");// 初始化主帐号名称和主帐号令牌
		restAPI.setAppId("8a48b5514fa577af014faadc93240f48");// 初始化应用ID
	}
	
    def sendSMS(mobile) {
		def smsV = SmsVerification.findOrCreateByMobile(mobile)
		def code = generatorCode()
		smsV.code = code
		smsV.lastUpdated = new Date()
		smsV.save flush:true
		
		String [] content = new String[2];
		content[0] = code
		content[1] = "5"
		HashMap<String, Object> result = null;
		//生产环境
		result = restAPI.sendTemplateSMS(mobile,"61813" ,content);

		System.out.println("SDKTestGetSubAccounts result=" + result);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}
			return true
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			return false
		}
		
		return true
    }
	
	def generatorCode(){
		def  seed = System.currentTimeMillis()
		def  random = new Random(seed)
		def code1 = random.nextInt(9)
		def code2 = random.nextInt(9)
		def code3 = random.nextInt(9)
		def code4 = random.nextInt(9)
		def code5 = random.nextInt(9)
		def code6 = random.nextInt(9)
		return code1.toString()+code2.toString()+code3.toString()+code4.toString()+code5.toString()+code6.toString()
	}
	
	def CodeCheck(String mobile, String code){
		def s = SmsVerification.findByMobile(mobile)
		def gson = new Gson()
		
		if(!s){
			gson.setResult(false)
			gson.setCode(401)
			gson.setInfo(["text":"验证码错误!"])
			return gson
		}
		
		if(!s.code.equals(code)){
			gson.setResult(false)
			gson.setCode(401)
			gson.setInfo(["text":"验证码错误!"])
			return gson
		}
		def now = new Date().time
		if(now > (s.lastUpdated.time + 1000*60*5)){
			gson.setResult(false)
			gson.setCode(401)
			gson.setInfo(["text":"验证码已失效！"])
			return gson
		}
		
		gson.setResult(true)
		gson.setCode(200)
		gson.setInfo(["text":"验证成功!"])
		return gson
	}
}
